package com.lenovo.nova.util.network;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeoutException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;

import com.lenovo.nova.util.debug.mylog;
import com.lenovo.nova.util.network.NetworkHelper.Method;
import com.lenovo.nova.util.network.NetworkHelper.NetworkManager;

/**
 * apache 联网的底层处理
 * 
 * @author liuzhd
 */
public class NetworkManagerJavaImp implements NetworkManager {
	private static final String HEADER_CONTENT_TYPE = "Content-Type";
	private static final String DEFAULT_PARAMS_ENCODING = "UTF-8";
	/**
	 * 网络超时时间
	 */
	private static final int CONNECT_TIMEOUT = 120 * 1000;

	/**
	 * 读取超时时间
	 */
	private static final int READ_TIMEOUT = 120 * 1000;
	private static final String TAG = NetworkManagerJavaImp.class.getSimpleName();

	public NetworkManagerJavaImp() {
	}

	@Override
	public HttpResponse connect(int method, String url, Map<String, String> requestHead, Map<String, String> postBody) throws SocketTimeoutException, ConnectException {

		URL parsedUrl = null;
		try {
			parsedUrl = new URL(url);
			mylog.i(TAG, "connect to url " + url);
		} catch (MalformedURLException e) {
			throw new RuntimeException("url error " + url);
		}
		HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) parsedUrl.openConnection();
		} catch (IOException e) {
			e.printStackTrace();
		}

		connection.setConnectTimeout(CONNECT_TIMEOUT);
		connection.setReadTimeout(READ_TIMEOUT);
		
		if(requestHead != null){
			for (String headerName : requestHead.keySet()) {
//				connection.addRequestProperty(headerName, requestHead.get(headerName));
                connection.setRequestProperty(headerName,requestHead.get(headerName));
				mylog.i(TAG, "headerName " + headerName + "  " + requestHead.get(headerName));
			}
		}
		setConnectionParametersForRequest(connection, method, postBody);
		// Initialize HttpResponse with data from the HttpURLConnection.
		ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
		int responseCode = 0;	
		try {
			responseCode = connection.getResponseCode();
			mylog.i(TAG, "responseCode " + responseCode);
		} catch (SocketTimeoutException e){
            throw e;
        }catch (ConnectException e){
            throw e;
        } catch (IOException e1) {
			e1.printStackTrace();
		}
        if (responseCode == -1) {
			// -1 is returned by getResponseCode() if the response code could
			// not be retrieved.
			// Signal to the caller that something was wrong with the
			// connection.
			try {
				throw new IOException("Could not retrieve response code from HttpUrlConnection.");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(responseCode != 200){
			mylog.e(TAG, "Error connect error ");
		}
		
		StatusLine responseStatus = null;
		try {
			responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage());
			mylog.i(TAG, "responseStatus " + responseStatus);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(responseStatus == null){
			return null;
		}
		BasicHttpResponse response = new BasicHttpResponse(responseStatus);
		response.setEntity(entityFromConnection(connection));
		for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
			if (header.getKey() != null) {
				Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
				response.addHeader(h);
			}
		}
		return response;

	}

	/**
	 * Initializes an {@link HttpEntity} from the given
	 * {@link HttpURLConnection}.
	 * 
	 * @param connection
	 * @return an HttpEntity populated with data from <code>connection</code>.
	 */
	private static HttpEntity entityFromConnection(HttpURLConnection connection) {
		BasicHttpEntity entity = new BasicHttpEntity();
		InputStream inputStream;
		try {
			inputStream = connection.getInputStream();
		} catch (IOException ioe) {
			mylog.e(TAG, "ioe " + ioe);
			inputStream = connection.getErrorStream();
		}
		entity.setContent(inputStream);
		entity.setContentLength(connection.getContentLength());
		entity.setContentEncoding(connection.getContentEncoding());
		entity.setContentType(connection.getContentType());
		return entity;
	}

	static void setConnectionParametersForRequest(HttpURLConnection connection, int method, Map<String, String> body) {
		try {
			switch (method) {
			case Method.GET:
				// Not necessary to set the request method because connection
				// defaults to GET but
				// being explicit here.
				connection.setRequestMethod("GET");
				break;
			case Method.POST:
				connection.setUseCaches(false);
				connection.setDoInput(true);
				connection.setRequestMethod("POST");
				addBodyIfExists(connection, body);
				break;
			default:
				throw new IllegalStateException("Unknown method type.");
			}
		} catch (ProtocolException e) {
			e.printStackTrace();
		}
	}

	private static byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
		if (params == null) {
			return null;
		}
		StringBuilder encodedParams = new StringBuilder();
		try {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
				encodedParams.append('=');
				encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
				encodedParams.append('&');
			}
			mylog.i(TAG, "encodedParams " + encodedParams.toString());
			return encodedParams.toString().getBytes(paramsEncoding);
		} catch (UnsupportedEncodingException uee) {
			throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
		}
	}

	private static void addBodyIfExists(HttpURLConnection connection, Map<String, String> mapBody) {
		try {
			byte[] body = encodeParameters(mapBody, "UTF-8");
			if (body != null) {
				connection.setDoOutput(true);
				connection.addRequestProperty(HEADER_CONTENT_TYPE, getBodyContentType());
				DataOutputStream out = new DataOutputStream(connection.getOutputStream());
				out.write(body);
				out.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected static String getParamsEncoding() {
		return DEFAULT_PARAMS_ENCODING;
	}

	/**
	 * Returns the content type of the POST or PUT body.
	 */
	public static String getBodyContentType() {
		return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
	}
}
